"""
    Author:
    Date: 2018-12-14

    SMS辅助函数。
"""
import qiniu
from utils.log import Log


def is_file_exist(access_key, secret_key, bucket_name, key):
    """ 判断文件是否在cdn上 """
    # 生成上传 Token，可以指定过期时间等
    q = qiniu.Auth(access_key, secret_key)
    # token = q.upload_token(bucket_name, key, 3600)

    # 判断文件是否已经存在
    bucket = qiniu.BucketManager(q)
    ret, info = bucket.stat(bucket_name, key)
    return ret and ('hash' in ret)


def get_upload_token(access_key, secret_key, bucket_name, key=None):
    """ 获取文件上传token """
    q = qiniu.Auth(access_key, secret_key)
    policy = {
        'fsizeMin': 1,
    }
    token = q.upload_token(bucket_name, key, 3600, policy)
    return token


def upload_file(access_key, secret_key, bucket_name, key, local_file):
    """
        local_file: 要上传的本地文件
        key: 上传到七牛后保存的文件名
    """
    # 生成上传 Token，可以指定过期时间等
    q = qiniu.Auth(access_key, secret_key)
    # policy = {
    #     'fsizeMin': 1,
    # }
    # token = q.upload_token(bucket_name, key, 3600, policy)
    token = get_upload_token(access_key, secret_key, bucket_name, key)

    # 判断文件是否已经存在
    bucket = qiniu.BucketManager(q)
    ret, info = bucket.stat(bucket_name, key)
    file_exist = ret and ('hash' in ret)
    if file_exist:
        return True

    # 上传文件
    ret, info = qiniu.put_file(token, key, local_file)
    Log.info(f'Upload {local_file} To CDN as {bucket_name}:{key} ...... ret={ret}.')
    if ret is None:
        Log.error(f'Upload {local_file} to CDN failed: {info}')
        return False

    # 检测上传结果
    if ret.get('key', '') != key:
        Log.error(f'Upload {local_file} to CDN failed: invalid key! ret={ret}, key={key}')
        return False

    local_hash = qiniu.etag(local_file)
    if ret.get('hash', '') != local_hash:
        Log.error(f'Upload {local_file} to CDN failed: invalid hash! ret={ret}, hash={local_hash}')
        return False

    # assert ret['key'] == key
    # assert ret['hash'] == qiniu.etag(local_file)
    if info.status_code != 200:
        Log.error(f'Upload {local_file} to CDN failed: {info}')
        return False

    Log.info(f'Upload {local_file} To CDN as {bucket_name}:{key} ...... OK ({info.status_code}).')
    return True


if __name__ == '__main__':
    print('ok')
